'use client'
import { useRouter, usePathname } from 'next/navigation'
import { useTranslation } from 'react-i18next'
import i18nConfig from '../../../../i18nConfig'

const LanguageChanger = () => {
    const { i18n } = useTranslation()
    const currentLocale = i18n.language
    const router = useRouter()
    const currentPathname = usePathname()
    const handleChange = (e: any) => {
        const newLocale = e.target.value
        const days = 30
        const date = new Date()
        date.setTime(date.getTime() + days * 24 * 3600 * 100)
        const expires = date.toUTCString()
        document.cookie = `NEXT_LOCALE=${newLocale};expires=${expires};path=/`
        if (currentLocale === i18nConfig.defaultLocale && !i18nConfig.prefixDefault) {
            router.push('/' + newLocale + currentPathname)
        } else {
            router.push(
                currentPathname.replace(`/${currentLocale}`, `/${newLocale}`)
            );
        }
        router.refresh()
    }
    return (
        <select onChange={handleChange} value={currentLocale}>
            <option value="en">English</option>
            <option value="zh">chinese</option>
        </select>
    )
}

export default LanguageChanger